use anyhow::Result;
use std::sync::Arc;
use sqlx::SqlitePool;
use chrono::{Utc, Duration};
use uuid::Uuid;

use crate::database::repository::{SessionRepository, SqliteSessionRepository};
use shared::types::Session;

#[derive(Clone)]
pub struct SessionService {
    session_repo: Arc<dyn SessionRepository>,
}

impl SessionService {
    pub fn new(pool: SqlitePool) -> Self {
        Self {
            session_repo: Arc::new(SqliteSessionRepository::new(pool)),
        }
    }
    
    /// 创建新会话
    pub async fn create_session(&self, user_id: i64, client_ip: String, client_port: u16) -> Result<Session> {
        let session_token = self.generate_session_token();
        let now = Utc::now();
        
        let session = Session {
            id: 0, // 数据库会自动分配
            user_id,
            session_token: session_token.clone(),
            client_ip,
            client_port,
            data_port: None,
            passive_port: None,
            transfer_mode: shared::types::TransferMode::Passive,
            current_directory: "/".to_string(),
            created_at: now,
            last_activity: now,
            is_active: true,
        };
        
        self.session_repo.create_session(&session).await
    }
    
    /// 验证会话
    pub async fn validate_session(&self, token: &str) -> Result<Option<Session>> {
        let session = self.session_repo.get_session_by_token(token).await?;
        
        if let Some(session) = session {
            if self.is_session_valid(&session) {
                // 更新最后活动时间
                let mut updated_session = session.clone();
                updated_session.last_activity = Utc::now();
                self.session_repo.update_session(&updated_session).await?;
                Ok(Some(updated_session))
            } else {
                // 会话过期，删除
                self.session_repo.delete_session(session.id).await?;
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }
    
    /// 更新会话
    pub async fn update_session(&self, session: &Session) -> Result<()> {
        self.session_repo.update_session(session).await
    }
    
    /// 删除会话
    pub async fn delete_session(&self, session_id: i64) -> Result<()> {
        self.session_repo.delete_session(session_id).await
    }
    
    /// 清理过期会话
    pub async fn cleanup_expired_sessions(&self) -> Result<u64> {
        self.session_repo.cleanup_expired_sessions().await
    }
    
    /// 检查会话是否有效
    fn is_session_valid(&self, session: &Session) -> bool {
        if !session.is_active {
            return false;
        }
        
        // 检查会话是否过期（24小时）
        let expiry_time = session.last_activity + Duration::hours(24);
        Utc::now() < expiry_time
    }
    
    /// 生成会话令牌
    fn generate_session_token(&self) -> String {
        Uuid::new_v4().to_string()
    }
}
